//
//  IdentityAuthenticationViewController.m
//  Exchange
//
//  Created by 张庆勇 on 2018/7/24.
//  Copyright © 2018年 张庆勇. All rights reserved.
//

#import "IdentityAuthenticationViewController.h"
#import "TGWebViewController.h"
#import "LLWebViewController.h"
#import "CountryModle.h"
#import "IdentityInfoViewController.h"
#import "CountryListsViewController.h"
@interface IdentityAuthenticationViewController ()
@property (nonatomic,strong)NSString *country_id;
@property (nonatomic,strong)NSString *country_code;
@property (nonatomic,strong)NSString *ID;//身份认证编号
@property (nonatomic,assign)NSInteger status;// 0代码第一次提交身信息 1代表=>已提交，2代表成功，3代表失败，4代表审核中
@property (nonatomic,assign)NSInteger method ;
@property (nonatomic,strong)NSMutableArray *dataArray;
@property (nonatomic,strong)NSArray *imageArray;
@end

@implementation IdentityAuthenticationViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self cussomUI];
    [self getidentityInfo];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getidentityInfo) name:SubimtVerificationDataNotificationse object:nil];
}
- (void)showLoadingAnimationWithIsShow:(BOOL)isShow
{
    if (isShow) {
        [self showLoadingAnimation];
        
    }else
    {
        [self stopLoadingAnimation];
   
    }
}
- (void)getcountry:(NSString *)country_id
{
    
     _country_id = country_id;
    [_dataArray removeAllObjects];
    WeakSelf
    [self GETWithHost:@"" path:countryHttp param:@{} cache:NO completed:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if ([responseObject[@"code"] integerValue] ==0)//成功
        {
            NSArray * list = responseObject[@"result"];
            for (NSDictionary * dic in list)
            {
                CountryModle * modle = [[CountryModle alloc] init];
                modle.CreatedAt = dic[@"CreatedAt"];
                modle.ID = dic[@"ID"];
                modle.UpdatedAt = dic[@"UpdatedAt"];
                modle.country_code = dic[@"code"];
                modle.is_show = dic[@"is_show"];
                modle.name_cn = dic[@"name_cn"];
                modle.name_en = dic[@"name_en"];
                modle.area_code = dic[@"area_code"];
                modle.pinyin = [self transform:[EXUnit removeCharacter:modle.name_cn]];
                [weakSelf.dataArray addObject:modle];
                if (modle.ID.integerValue ==country_id.integerValue)
                {
                    weakSelf.countryLable.text = [NSString stringWithFormat:@"%@ (%@)",modle.name_cn,modle.area_code];
                }
            }
          
             [self showLoadingAnimationWithIsShow:NO];
        }else
        {
            [self axcBasePopUpWarningAlertViewWithMessage:responseObject[@"message"] view:kWindow];
        }
    } error:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
- (NSString *)transform:(NSString *)chinese{
    //将NSString装换成NSMutableString
    NSMutableString *pinyin = [chinese mutableCopy];
    
    //将汉字转换为拼音(带音标)
    CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformMandarinLatin, NO);
    
    //去掉拼音的音标
    CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformStripCombiningMarks, NO);
    NSLog(@"%@", pinyin);
    
    //返回最近结果
    return pinyin;
    
}
// 第一次获取认证信息
- (void)getidentityInfo
{
    [self GETWithHost:@"" path:identity param:@{} cache:NO completed:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"code"] integerValue]==0)//成功
        {
            self.status = [responseObject[@"result"][@"info"][@"status"] integerValue];
            if (self.status!=1)
            {
                [self getcountry:@"44"];
            }else if (self.status==1)
            {
                self.ID = responseObject[@"result"][@"info"][@"ID"];
                self.country_id = responseObject[@"result"][@"info"][@"country_id"];
                self.nameField.text =responseObject[@"result"][@"info"][@"first_name"];
                self.surnameField.text =responseObject[@"result"][@"info"][@"last_name"];
                self.idField.text =responseObject[@"result"][@"info"][@"number"];
                self.method = [responseObject[@"result"][@"info"][@"method"] integerValue];
                self.imageArray = responseObject[@"result"][@"images"];
                self.country_code = responseObject[@"result"][@"info"][@"country_code"];
                [self getcountry:self.country_id];
            }
            self.submitButton.enabled=YES;
            self.submitButton.alpha = 1;
           
            
        }
        
    } error:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
- (void)cussomUI
{
    [self showLoadingAnimationWithIsShow:YES];
    self.view.backgroundColor = MainBGCOLOR;
    _bgView3.backgroundColor = textFieldColor;
    _bgView2.backgroundColor = textFieldColor;
    _bgView1.backgroundColor = textFieldColor;
    _bgView.backgroundColor = textFieldColor;
    _submitButton.backgroundColor = TABTITLECOLOR;
    self.messageLable.hidden = YES;
    _countryTitleLable.text = Localized(@"Authentication_international");
    _nameTitleLable.text = Localized(@"Authentication_surname");
    _nameField.placeholder=Localized(@"Authentication_lastname");
    _surnameTitleLable.text = Localized(@"Authentication_appellation");
    _surnameField.placeholder = Localized(@"Authentication_name");
    _idTitlelable.text = Localized(@"Authentication_ID_number1");
    _idField.placeholder = Localized(@"Authentication_ID_number");
    [_submitButton setTitle:Localized(@"Security_Next_step") forState:0];
    [_nameField setValue:textFieldPCOLOR forKeyPath:@"_placeholderLabel.textColor"];
    [_nameField setValue:AutoFont(13) forKeyPath:@"_placeholderLabel.font"];
    _nameField.tintColor = MAINTITLECOLOR;
    _nameField.textColor = MAINTITLECOLOR;
    
    [_surnameField setValue:textFieldPCOLOR forKeyPath:@"_placeholderLabel.textColor"];
    [_surnameField setValue:AutoFont(13) forKeyPath:@"_placeholderLabel.font"];
    _surnameField.tintColor = TABTITLECOLOR;
    _surnameField.textColor =MAINTITLECOLOR;
    
    [_idField setValue:textFieldPCOLOR forKeyPath:@"_placeholderLabel.textColor"];
    [_idField setValue:AutoFont(13) forKeyPath:@"_placeholderLabel.font"];
     _idField.tintColor = TABTITLECOLOR;
    _idField.textColor = MAINTITLECOLOR;
    _countryLable.textColor = MAINTITLECOLOR;
    
    KViewRadius(self.submitButton, 2);
}
- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (IBAction)submitButton:(UIButton *)sender {
    
    if ([NSString isEmptyString:_nameField.text])
    {
        
        [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"Authentication_lastname") view:kWindow];
        return;
    }
    if ([NSString isEmptyString:_surnameField.text])
    {
        [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"Authentication_name") view:kWindow];
        return;
    }
    if ([NSString isEmptyString:_idField.text])
    {
        [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"Authentication_ID_number") view:kWindow];
        return;
    }
     if (![EXUnit isSpaceWithstr:_idField.text])
    {
        [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"Authentication_numbers_symbols_message") view:kWindow];
        return;
    }
  
    if (self.status!=1)
    {
        WeakSelf
        [self POSTWithHost:@"" path:identity param:@{@"first_name":[EXUnit removeSpecialWithText:_nameField.text] ,@"country_id":_country_id,@"last_name":[EXUnit removeSpecialWithText:_surnameField.text],@"number":[EXUnit removeSpecialWithText:_idField.text]} cache:NO completed:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if ([responseObject[@"code"] integerValue]==0)//成功
            {
                // 身份认证方式 0为自动，1为手动 // 如果为手动则返回为空，否则返回第三方请求地址
                NSInteger method = [responseObject[@"result"][@"method"] integerValue];
                 weakSelf.ID = responseObject[@"result"][@"id"];
                 weakSelf.status =1;
                 weakSelf.method = [responseObject[@"result"][@"method"] integerValue];
                if (method ==0)
                {
                    LLWebViewController *webV = [LLWebViewController new];
                    webV.urlStr = responseObject[@"result"][@"url"];
                    webV.isPullRefresh = YES;
                    [self.navigationController pushViewController:webV animated:YES];
                }else
                {
                    IdentityInfoViewController *identityInfoVC  = [[IdentityInfoViewController alloc] init];
                    identityInfoVC.title= Localized(@"Authentication_information_message");
                    identityInfoVC.identity_id = responseObject[@"result"][@"id"];
                     identityInfoVC.country_code = weakSelf.country_code;
                    identityInfoVC.country_id = weakSelf.country_id;
                    [self.navigationController pushViewController:identityInfoVC animated:YES];
                }
                
                
            }else
            {
                [self axcBasePopUpWarningAlertViewWithMessage:responseObject[@"message"] view:kWindow];
            }
            
        } error:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
    }else if (self.status==1)
    {
        WeakSelf
        if ([NSString isEmptyString:_ID])
        {
            [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"Authentication_Failed_message") view:kWindow];
            return;
        }
        [self POSTWithHost:@"" path:updateIdentity param:@{@"id":_ID,@"first_name":_nameField.text,@"country_id":_country_id,@"last_name":_surnameField.text,@"number":_idField.text} cache:NO completed:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if ([responseObject[@"code"] integerValue]==0)//成功
            {
                // 身份认证方式 0为自动，1为手动 // 如果为手动则返回为空，否则返回第三方请求地址
               
                if (weakSelf.method ==0)
                {
                    
                    LLWebViewController *webV = [LLWebViewController new];
                    webV.urlStr = responseObject[@"result"][@"url"];
                    webV.isPullRefresh = YES;
                    [self.navigationController pushViewController:webV animated:YES];
                }else
                {
                    IdentityInfoViewController *identityInfoVC  = [[IdentityInfoViewController alloc] init];
                    identityInfoVC.title=Localized(@"Authentication_information_message");
                    identityInfoVC.imgArray = self.imageArray;
                    identityInfoVC.identity_id = weakSelf.ID;
                    identityInfoVC.country_code = weakSelf.country_code;
                    identityInfoVC.country_id = weakSelf.country_id;
                    [self.navigationController pushViewController:identityInfoVC animated:YES];
                }
                
                
            }else
            {
                [self axcBasePopUpWarningAlertViewWithMessage:responseObject[@"message"] view:kWindow];
            }
            
        } error:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
    }
    
   
}

- (IBAction)chooseCountry:(UIButton *)sender {
    
    WeakSelf    
    CountryListsViewController * CountryListVC = [[CountryListsViewController alloc] init];
    CountryListVC.dataArray = self.dataArray;
    CountryListVC.index = self.country_id.integerValue;
    [self presentViewController:CountryListVC animated:YES completion:nil];
    CountryListVC.selectIndexPathRow = ^(CountryModle *modle) {
        self.country_id = modle.ID;
        if ([[EXUnit  isLocalizable]  hasPrefix:@"zh-Hant"] || [[EXUnit  isLocalizable]  hasPrefix:@"zh-Hans"] ) {
           weakSelf.countryLable.text = [NSString stringWithFormat:@"%@ %@",modle.name_cn,modle.area_code];
        }else
        {
            weakSelf.countryLable.text = [NSString stringWithFormat:@"%@ %@",modle.name_en,modle.area_code];
        }
    };
}
@end
